/**
 * 设置工具类
 * 提供设置相关的常用操作和工具函数
 * 注意：主要功能已迁移到 @/config/unified-settings.ts
 */

import type { AppSettings, SettingsItem } from '@/types/settings'
import type { SettingsCategory } from '@/config/unified-settings'
import { 
  unifiedSettings as DEFAULT_SETTINGS,
  SETTINGS_CATEGORIES,
  getSettingValue as getUnifiedSettingValue,
  setSettingValue as setUnifiedSettingValue,
  mergeSettings as mergeUnifiedSettings,
  validateUnifiedSettings as validateUnifiedSettingsFunc,
  resetSettings as resetUnifiedSettings
} from '@/config/unified-settings'

// 重新导出统一设置功能
export { 
  DEFAULT_SETTINGS,
  SETTINGS_CATEGORIES,
  getUnifiedSettingValue as getSettingValue,
  setUnifiedSettingValue as setSettingValue,
  mergeUnifiedSettings as mergeSettings,
  validateUnifiedSettingsFunc as validateSettings,
  resetUnifiedSettings as resetSettings
}

// 设置项配置
export const SETTINGS_ITEMS: SettingsItem[] = [
  // 主题设置
  {
    key: 'theme.mode',
    title: '主题模式',
    description: '选择界面主题模式',
    type: 'select',
    value: 'light',
    defaultValue: 'light',
    options: [
      { label: '亮色', value: 'light' },
      { label: '暗色', value: 'dark' },
      { label: '跟随系统', value: 'auto' }
    ],
    category: 'theme',
    order: 1
  },
  {
    key: 'theme.primaryColor',
    title: '主色调',
    description: '设置系统主色调',
    type: 'color',
    value: '#409EFF',
    defaultValue: '#409EFF',
    category: 'theme',
    order: 2
  },
  {
    key: 'theme.borderRadius',
    title: '圆角大小',
    description: '设置界面元素圆角大小',
    type: 'select',
    value: 'medium',
    defaultValue: 'medium',
    options: [
      { label: '无', value: 'none' },
      { label: '小', value: 'small' },
      { label: '中', value: 'medium' },
      { label: '大', value: 'large' }
    ],
    category: 'theme',
    order: 3
  },
  
  // 界面设置
  {
    key: 'interface.sidebarMode',
    title: '侧边栏模式',
    description: '选择侧边栏布局模式',
    type: 'select',
    value: 'vertical',
    defaultValue: 'vertical',
    options: [
      { label: '垂直', value: 'vertical' },
      { label: '水平', value: 'horizontal' },
      { label: '混合', value: 'mix' }
    ],
    category: 'interface',
    order: 1
  },
  {
    key: 'interface.sidebarCollapsed',
    title: '默认折叠侧边栏',
    description: '设置侧边栏默认是否折叠',
    type: 'boolean',
    value: false,
    defaultValue: false,
    category: 'interface',
    order: 2
  },
  {
    key: 'interface.pageSize',
    title: '页面大小',
    description: '设置列表页面默认显示条数',
    type: 'select',
    value: 10,
    defaultValue: 10,
    options: [
      { label: '10条/页', value: 10 },
      { label: '20条/页', value: 20 },
      { label: '50条/页', value: 50 },
      { label: '100条/页', value: 100 }
    ],
    category: 'interface',
    order: 3
  },
  
  // 语言设置
  {
    key: 'language.locale',
    title: '界面语言',
    description: '设置界面显示语言',
    type: 'select',
    value: 'zh-cn',
    defaultValue: 'zh-cn',
    options: [
      { label: '中文', value: 'zh-cn' },
      { label: 'English', value: 'en' }
    ],
    category: 'language',
    order: 1
  },
  
  // 通知设置
  {
    key: 'notification.enableSound',
    title: '启用声音',
    description: '启用通知声音提示',
    type: 'boolean',
    value: true,
    defaultValue: true,
    category: 'notification',
    order: 1
  },
  {
    key: 'notification.enableDesktop',
    title: '桌面通知',
    description: '启用桌面通知',
    type: 'boolean',
    value: true,
    defaultValue: true,
    category: 'notification',
    order: 2
  },
  {
    key: 'notification.soundVolume',
    title: '音量大小',
    description: '设置通知音量大小',
    type: 'number',
    value: 50,
    defaultValue: 50,
    min: 0,
    max: 100,
    step: 1,
    category: 'notification',
    order: 3
  }
]

/**
 * 获取设置值
 * @param settings 设置对象
 * @param path 设置路径，如 'theme.mode'
 * @returns 设置值
 */
export function getSettingValueByPath(settings: AppSettings, path: string): unknown {
  const keys = path.split('.')
  let current: unknown = settings
  
  for (const key of keys) {
    if (current && typeof current === 'object' && current !== null && key in current) {
      current = (current as Record<string, unknown>)[key]
    } else {
      return undefined
    }
  }
  
  return current
}

/**
 * 设置值
 * @param settings 设置对象
 * @param path 设置路径，如 'theme.mode'
 * @param value 设置值
 */
export function setSettingValueByPath(settings: AppSettings, path: string, value: unknown): void {
  const keys = path.split('.')
  let current: Record<string, unknown> = settings as unknown as Record<string, unknown>
  
  for (let i = 0; i < keys.length - 1; i++) {
    const key = keys[i]
    if (!current[key] || typeof current[key] !== 'object' || current[key] === null) {
      current[key] = {}
    }
    current = current[key] as Record<string, unknown>
  }
  
  current[keys[keys.length - 1]] = value
}

/**
 * 合并设置
 * @param target 目标设置
 * @param source 源设置
 * @returns 合并后的设置
 */
export function mergeSettingsObjects(target: AppSettings, source: Partial<AppSettings>): AppSettings {
  return {
    ...target,
    ...source,
    theme: { ...target.theme, ...source.theme },
    interface: { ...target.interface, ...source.interface },
    language: { ...target.language, ...source.language },
    notification: { 
      ...target.notification, 
      ...source.notification,
      notificationTypes: { 
        ...target.notification.notificationTypes, 
        ...source.notification?.notificationTypes 
      }
    },
    security: { ...target.security, ...source.security },
    performance: { ...target.performance, ...source.performance },
    system: { ...target.system, ...source.system },
    data: { ...target.data, ...source.data },
    integration: { ...target.integration, ...source.integration }
  }
}

/**
 * 验证设置值
 * @param settings 设置对象
 * @returns 验证结果
 */
export function validateSettingsValues(settings: AppSettings): { valid: boolean; errors: string[] } {
  const errors: string[] = []
  
  // 验证主题设置
  if (!['light', 'dark', 'auto'].includes(settings.theme.mode)) {
    errors.push('主题模式必须是 light、dark 或 auto')
  }
  
  if (!/^#[0-9A-Fa-f]{6}$/.test(settings.theme.primaryColor)) {
    errors.push('主色调必须是有效的十六进制颜色值')
  }
  
  if (!['none', 'small', 'medium', 'large'].includes(settings.theme.borderRadius)) {
    errors.push('圆角大小必须是 none、small、medium 或 large')
  }
  
  // 验证界面设置
  if (!['vertical', 'horizontal', 'mix'].includes(settings.interface.sidebarMode)) {
    errors.push('侧边栏模式必须是 vertical、horizontal 或 mix')
  }
  
  if (![10, 20, 50, 100].includes(settings.interface.pageSize)) {
    errors.push('页面大小必须是 10、20、50 或 100')
  }
  
  // 验证语言设置
  if (!settings.language.availableLocales.includes(settings.language.locale)) {
    errors.push('界面语言必须在可用语言列表中')
  }
  
  // 验证通知设置
  if (settings.notification.soundVolume < 0 || settings.notification.soundVolume > 100) {
    errors.push('音量大小必须在 0-100 之间')
  }
  
  // 验证安全设置
  if (settings.security.sessionTimeout < 5 || settings.security.sessionTimeout > 1440) {
    errors.push('会话超时时间必须在 5-1440 分钟之间')
  }
  
  if (settings.security.maxLoginAttempts < 3 || settings.security.maxLoginAttempts > 10) {
    errors.push('最大登录尝试次数必须在 3-10 之间')
  }
  
  // 验证性能设置
  if (settings.performance.cacheExpiry < 60 || settings.performance.cacheExpiry > 86400) {
    errors.push('缓存过期时间必须在 60-86400 秒之间')
  }
  
  if (settings.performance.maxConcurrentRequests < 1 || settings.performance.maxConcurrentRequests > 50) {
    errors.push('最大并发请求数必须在 1-50 之间')
  }
  
  return {
    valid: errors.length === 0,
    errors
  }
}

/**
 * 导出设置到JSON字符串
 * @param settings 设置对象
 * @returns 导出的设置字符串
 */
export function exportSettingsToJson(settings: AppSettings): string {
  const exportData = {
    version: '1.0.0',
    timestamp: new Date().toISOString(),
    settings,
    metadata: {
      exportedBy: 'system',
      exportedAt: new Date().toISOString(),
      systemVersion: '1.0.0'
    }
  }
  
  return JSON.stringify(exportData, null, 2)
}

/**
 * 从JSON字符串导入设置
 * @param data 设置数据字符串
 * @returns 解析后的设置对象
 */
export function importSettingsFromJson(data: string): AppSettings {
  try {
    const parsed = JSON.parse(data)
    
    if (!parsed.settings) {
      throw new Error('无效的设置文件格式')
    }
    
    return mergeSettingsObjects(DEFAULT_SETTINGS, parsed.settings)
  } catch (error) {
    throw new Error(`设置文件解析失败: ${(error as Error).message}`)
  }
}

/**
 * 重置设置到默认值
 * @param category 设置分类，可选
 * @returns 重置后的设置对象
 */
export function resetSettingsToDefault(category?: string): AppSettings {
  if (category) {
    const resetSettings = { ...DEFAULT_SETTINGS }
    // 只重置指定分类的设置
    return resetSettings
  }
  
  return { ...DEFAULT_SETTINGS }
}

/**
 * 获取设置分类
 * @param categoryKey 分类键
 * @returns 设置分类对象
 */
export function getSettingsCategory(categoryKey: string): SettingsCategory | undefined {
  return SETTINGS_CATEGORIES.find(cat => cat.key === categoryKey)
}

/**
 * 获取设置项
 * @param category 分类，可选
 * @returns 设置项数组
 */
export function getSettingsItems(category?: string): SettingsItem[] {
  if (category) {
    return SETTINGS_ITEMS.filter(item => item.category === category)
  }
  
  return SETTINGS_ITEMS
}

/**
 * 获取设置项
 * @param key 设置项键
 * @returns 设置项对象
 */
export function getSettingsItem(key: string): SettingsItem | undefined {
  return SETTINGS_ITEMS.find(item => item.key === key)
}

/**
 * 检查设置是否已修改
 * @param current 当前设置
 * @param original 原始设置
 * @returns 是否已修改
 */
export function isSettingsChanged(current: AppSettings, original: AppSettings): boolean {
  return JSON.stringify(current) !== JSON.stringify(original)
}

/**
 * 获取设置变更摘要
 * @param current 当前设置
 * @param original 原始设置
 * @returns 变更摘要
 */
export function getSettingsChangeSummary(current: AppSettings, original: AppSettings): Array<{ path: string; oldValue: unknown; newValue: unknown }> {
  const changes: Array<{ path: string; oldValue: unknown; newValue: unknown }> = []
  
  // 比较各个设置分类
  const categories = ['theme', 'interface', 'language', 'notification', 'security', 'performance', 'system', 'data', 'integration']
  
  for (const category of categories) {
    const currentCategory = current[category as keyof AppSettings]
    const originalCategory = original[category as keyof AppSettings]
    
    if (JSON.stringify(currentCategory) !== JSON.stringify(originalCategory)) {
      // 这里可以进一步比较具体的字段
      changes.push({
        path: category,
        oldValue: originalCategory,
        newValue: currentCategory
      })
    }
  }
  
  return changes
}
